public class HashBuck {
    static class Node {
        public int key;
        public int val;
        public Node next;
        public Node(int key,int val) {
            this.key = key;
            this.val = val;
        }
    }
    public Node[] array = new Node[10];
    public int usedSize;
    public final static double LOAD_DEFAULT = 0.75;
    /**
     * 插入元素
     * @param key
     * @param val
     *      1.判断是否已经插入元素,插入,修改value
     *      2.否,进行除取余数,找到合适下标,如果已经存在元素,进行头插
     *      3.判断是否超过阀值,超过,扩容,并对元素进行重新调整
     */
    public void push(int key,int val) {
        Node node = new Node(key,val);

        int index = key % array.length;
        //判断是否存在
        Node cur = array[index];
        while(cur != null) {
            if(cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //不存在
        node.next = array[index];
        array[index] = node;
        usedSize++;
        //判断是否超过阀值
        if(loadFactor() >= LOAD_DEFAULT) {
            //重新调整
            reSize();
        }
    }

    /**
     * 重新调整
     *      1.遍历原数组
     *      2.遇到哈希桶,进入链表,遍历,重新分布位置
     */
    private void reSize() {
        Node[] newArray = new Node[array.length * 2];
        for(int i = 0;i < array.length;i++) {
            Node cur = array[i];
            while(cur != null) {
                Node curNext = cur.next;
                int index = cur.key % newArray.length;
                //头插
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curNext;
            }
        }
        array = newArray;
    }
    private double loadFactor() {
        return usedSize * 1.0 / array.length;
    }
    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null) {
            if(cur.key == key) {
                return cur.val;
            }
        }
        return -1;
    }
}
